<!--
  用户登录界面
-->
<template>
  <div>
    <h1>{{ msg }}</h1>
    <el-row>
      <el-col :span="8" :push="8">
        <el-form ref="form" :model="user" label-width="80px" status-icon :rules="rules" >
          <el-form-item label="手机号:" prop="phoneNumber">
            <el-input v-model="user.phoneNumber" placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone"></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input v-model="user.password" show-password placeholder="请输入密码" prefix-icon="el-icon-lock"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="login" type="primary" plain>登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import instance from "../utils/request";

export default {
  name: "Login",
  data(){
    return {
      msg: '用户登录',
      user:{
        phoneNumber:'',
        password:''
      },
      /*
      表单验证规则
       */
      rules:{
        phoneNumber: [
          {required:true, message:'请输入手机号', trigger: 'blur'},
          {min:11, max:11}
        ],
        password:[
          {required:true, message:'请输入密码', trigger: 'blur'},
          {min:3, max:12}
        ]
      }
    }
  },
  methods:{
    /*
      登录方法
     */
    login(){
      if(!this.user.phoneNumber || !this.user.password){
        alert('请完善输入信息');
        return;
      }
      var _this = this;
      // Cookie跨域
      instance.defaults.withCredentials = true
      instance.post('/api/worker/login',{
        phoneNumber:_this.user.phoneNumber,
        password:_this.user.password
      }).then(function (res){
        if(res.data.code === 200){
          console.log('登录成功');
          alert('登录成功');
          /*
          登录成功操作：
              修改登录状态
              设置当前登录用户id，密码
              跳转用户主页
           */
          _this.$store.commit('changeLogin_Status');
          _this.$store.commit('setId',_this.user.phoneNumber);
          _this.$store.commit('setPswd',_this.user.password);
          _this.$router.push({name:'Worker'});
        }
        else if(res.data.code === 202){
          alert('账户名或密码错误！');
          _this.user={};
        }
        else {
          alert('出错啦，请刷新后重试');
          _this.user={};
        }
        console.log(res.data);
      }).catch(function (err) {
        console.log(err);
        alert('出错啦，请刷新后重试');
        _this.user = {};
      });
    }
  }
}
</script>

<style scoped>

</style>
